#   Copyright 2006 Jerome Lacoste (jerome@coffeebreaks.org)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
module IssueTracker

#  class UnrecognizedIssueId < StandardError
#  end

#      raise UnrecognizedIssueId, issueid + ' not a ' + @name + ' issue ID' if ! match? issueid

  class InvalidURL < StandardError
  end

  class Tracker

    attr_reader :name

    def initialize(name, url, id_matcher)
      raise InvalidURL, "InvalidURL: " + url unless url =~ Regexp.new("http(s|):.+$", true)
      @name = name
      url +=  '/' if url.last(1) != '/'
      @url = url
      @id_matcher = Regexp.new(id_matcher)
    end

    def match?(issueid)
      issueid =~ @id_matcher
    end

    #
    # Requires implementation of get_issue_url(id) where id is the first pattern identified
    # in the specified text argument that matches the id_matcher pattern
    def to_html(text)
      text.gsub(@id_matcher) { |id| "<a href='" + get_issue_url($1) + "'>" + id + "</a>" }
    end

    # this is not very ruby-like. FIXME
    def self.get(name, url, pattern = nil)
      raise StandardError, "null name" unless name
      if name == "Jira"
        if pattern
          res = Jira.new(url, pattern)
        else
          res = Jira.new(url)
        end
      elsif name == "Bugzilla"
        if pattern
          res = Bugzilla.new(url, pattern)
        else
          res = Bugzilla.new(url)
        end
      end
      raise StandardError, "Unknown Tracker " + name unless res
      res
    end

    def self.supported_tracker_names
      [ "Jira", "Bugzilla" ]
    end
  end  

  class Jira < Tracker
    def initialize(url, pattern = "([A-Z][A-Z][A-Z]-[0-9]+)")
      super("Jira", url, pattern)
    end

    def get_issue_url(issueid)
      return @url + "browse/" + issueid
    end

  end

  class Bugzilla < Tracker
    def initialize(url, pattern = "([0-9]+)")
      super("Bugzilla", url, pattern)
    end

    def get_issue_url(issueid)
      return @url + "show_bug.cgi?id=" + issueid
    end
  end
end
